// src/api/service/ProductService.tsx
import {
    GET_PRODUCTS,
    GET_PRODUCT_BY_ID,
    CREATE_PRODUCT, DELETE_PRODUCT, UPDATE_PRODUCT, fetchQueryProductList,
} from '../gql/ProductGQL';
import graphqlClient from '../../api/GraphqlConfig';

class ProductService {
    /**
     * 获取商品列表
     * @param limit 每页数量
     * @param cursor 游标
     * @returns 商品列表响应
     */
    async getProducts(limit: number = 20, cursor?: string): Promise<ProductListResponse> {
        try {
            const result = await graphqlClient.query<{ product: ProductListResponse }>({
                query: GET_PRODUCTS,
                variables: { limit, cursor }
            });
            return result.data!.product;
        } catch (error) {
            console.error('获取商品列表失败:', error);
            throw error;
        }
    }

    /**
     * 根据ID获取商品详情
     * @param id 商品ID
     * @returns 商品详情
     */
    async getProductById(id: number): Promise<Product> {
        try {
            const result = await graphqlClient.query<{ product: { productById: Product } }>({
                query: GET_PRODUCT_BY_ID,
                variables: { id }
            });
            // 修复 getProductById
            return result.data!.product.productById;
        } catch (error) {
            console.error('获取商品详情失败:', error);
            throw error;
        }
    }

    /**
     * 创建商品
     * @param input 商品信息
     * @returns 创建的商品
     */
    async createProduct(input: CreateProductInput): Promise<Product> {
        try {
            const result = await graphqlClient.mutate<{ product: { createProduct: Product } }>({
                mutation: CREATE_PRODUCT,
                variables: {
                    title: input.title,
                    description: input.description,
                    detailAddr: input.detailAddr,
                    coverAddr: input.coverAddr,
                    price: input.price,
                    rate: input.rate,
                    status: input.status,
                    stockpile: input.stockpile,
                    specifications: input.specifications
                }
            });
            return result.data!.product.createProduct;
        } catch (error) {
            console.error('创建商品失败:', error);
            throw error;
        }
    }

    /**
     * 更新商品
     * @param id 商品ID
     * @param input 商品信息
     * @returns 更新的商品
     */
    async updateProduct(id: number, input: UpdateProductInput): Promise<Product> {

        try {
            const result = await graphqlClient.mutate<{ product: { updateProduct: Product } }>({
                mutation: UPDATE_PRODUCT,
                variables: {
                    id: id,
                    title: input.title,
                    description: input.description,
                    detailAddr: input.detailAddr,
                    coverAddr: input.coverAddr,
                    price: input.price,
                    rate: input.rate,
                    status: input.status,
                    stockpile: input.stockpile,
                    specifications: input.specifications
                }
            })
            return result.data!.product.updateProduct;
        } catch (e) {

            console.log("更新商品失败：", e);
            throw e;
        }

    }

    /**
     * 获取商品列表（使用 fetchQueryProductList 查询）
     * @param keyword
     * @param limit 每页数量
     * @param cursor 游标
     * @returns 商品列表响应
     */
    async fetchProductList(keyword: string, limit: number = 20, cursor?: string): Promise<ProductListResponse> {
        try {
            const result = await graphqlClient.query<{ product: ProductListResponse }>({
                query: fetchQueryProductList,
                variables: { keyword, limit, cursor }
            });
            return result.data!.product;
        } catch (error) {
            console.error('获取商品列表失败:', error);
            throw error;
        }
    }


    /**
     * 删除商品
     * @param id 商品ID
     * @returns 删除结果
     */
    async deleteProduct(id: number): Promise<boolean> {
        try {
            const result = await graphqlClient.mutate<{ product: { deleteProduct: boolean } }>({
                mutation: DELETE_PRODUCT,
                variables: { id }
            });
            return result.data!.product.deleteProduct;
        } catch (e) {
            console.log("删除商品失败：", e);
            throw e;
        }
    }

}


// 商品数据类型定义
export interface Product {
    id: number;
    title: string;
    description: string;
    detailAddr: string;
    coverAddr: string;
    price: number;
    rate: number;
    status: string;
    stockpile: number;
    stockpileFrozen: number;
    createTime: string;
    updateTime: string;
    specifications: ProductSpecification[];
}

export interface ProductSpecification {
    id: number;
    item: string;
    value: string;
    productId: number;
    createTime: string;
    updateTime: string;
}

// 创建商品的输入类型
export interface ProductSpecificationInput {
    item: string;
    value: string;
}

export interface CreateProductInput {
    title: string;
    description?: string;
    detailAddr?: string;
    coverAddr?: string;
    price: string; // 注意：这里使用 string 类型，与 GraphQL schema 一致
    rate?: string;
    status: string;
    stockpile: number;
    specifications?: ProductSpecificationInput[];
}

export interface UpdateProductInput {
    title: string;
    description?: string;
    detailAddr?: string;
    coverAddr?: string;
    price: string; // 注意：这里使用 string 类型，与 GraphQL schema 一致
    rate?: string;
    status: string;
    stockpile: number;
    specifications?: UpdateProductSpecificationInput[];
}
export interface UpdateProductSpecificationInput {
    id?: string;
    item: string;
    value: string;
}



export interface ProductListResponse {
    productList: {
        hasNext: boolean;
        nextCursor: string;
        products: Product[];
    };
}



// 创建并导出 ProductService 实例
export const productService = new ProductService();
